//
//  OAuthViewController.swift
//  SinaMicroBlog
//
//  Created by wxy on 15/9/3.
//  Copyright © 2015年 wxy. All rights reserved.
//

import UIKit
import SVProgressHUD

/// OAuth授权控制器
class OAuthViewController: UIViewController,UIWebViewDelegate {

    private lazy var webView = UIWebView()

    //一般创建视图层次结构时，在loadView比较好
    override func loadView() {
        
        //替换根视图
        view = webView
        
        //MARK: - 又忘记设置代理了
        webView.delegate = self
        
        title = "登陆新浪微博"
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "关闭", style: UIBarButtonItemStyle.Plain, target: self, action: "close")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "自动登录", style: UIBarButtonItemStyle.Plain, target: self, action: "autoLogin")
    }
    
    @objc private func close() {
        
        SVProgressHUD.dismiss()
        
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    @objc private func autoLogin() {
        
        let js = "document.getElementById('userId').value = '18632536757';" +
        "document.getElementById('passwd').value = 'Wxy%^36757';"
        
        webView.stringByEvaluatingJavaScriptFromString(js)
        
        }
    //尽量让控制器不要管太多的事情
    override func viewDidLoad() {
        
        super.viewDidLoad()
        //webView发送请求
        webView.loadRequest(NSURLRequest(URL: NetworkTools.sharedNetworkTools.OAuthURL))
    }
    
    //MARK: - UIWebViewDelegate
    //获取请求码，根据请求码选择跳转
    //代理方法有BOOL类型返回值 ，返回true通常一切正常
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool {
        
        //获取网址的全部字符
        let urlStr = request.URL!.absoluteString
        
        //1.判断 request.url的前半部分是否是回调地址，如果不是回调地址，继续加载
        if !urlStr.hasPrefix(NetworkTools.sharedNetworkTools.redirectUri) {
            return true
        }
        
        //2.如果是回调地址，检查query是否包含 "code="
        //query 就是URL中?后面的内容
        if let query = request.URL!.query where query.hasPrefix("code=") {
            //3.如果有，获取code
            let code = query.substringFromIndex("code=".endIndex)
            
            printLog("请求码 + code")
            
            //4.调用网络方法获取token
            UserAccountViewModel.sharedUserAccount.loadUserAccount(code).subscribeError({ (error) -> Void in
                
                printLog(error)
                
                }, completed: { () -> Void in
                    
                    printLog("登陆成功")
                    
                    // 切换到Welcome
                    NSNotificationCenter.defaultCenter().postNotificationName(SwitchRootViewControllerNotification, object: "Welcome")
            })
        }else{
            printLog("取消")
        }
        
        return false
    }
    
    //网络加载弹窗
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.show()
    }
    
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
}
